<?php

namespace Admin\Frontend\Controllers;

use Admin\Models\sys\XhsysClassification;
use Composer\IO\NullIO;
use Helpers\Tool;
use Helpers\Main;
use Helpers\UserPower;
use Helpers\Template;
use Helpers\Assets;
use Admin\Models\sys\XhsysEnum;
use Admin\Models\faq\XhfaqInfo;
use Modules\Power;
use Services\App;
use stdClass;
use Exception;

class FaqController extends ControllerBase
{
    private $typenum = [
        'bPublic' => [1 => '是', 0 => '否'],
        'iTarget' => [1 => '常见问题', 2 => '使用说明']
    ];
    /**
     * FAQ列表页面
     *
     * create by ck 20160713
     * modify by ck 20160913    结构更改
     */
    public function indexAction()
    {
        Assets::FroalaEditor();
        Main::showNavPosition();
        UserPower::checkUserPower('Faq') or die(Main::showMessageModal('对不起，您没有查看此页面的权限！', 109104001));
        Template::exists('XHFaq_Info', 'both') or die(Main::showMessageModal('配置文件不存在，请先创建！', 109104002));
        $listButtonArr = $formButtonArr = $listSearchArr = [];
        if (UserPower::checkUserPower('Faq_Add')) {
            $listButtonArr[] = ['id'=>'bt_list_add', 'text'=>'增加', 'plain'=>'true', 'icon'=>'fa-plus'];
            $formButtonArr[] = ['id'=>'bt_form_add', 'text'=>'增加', 'class'=>'disabled'];
            $this->view->setVar('AddEdit', true);
        }
        if (UserPower::checkUserPower('Faq_Edit')) {
            $formButtonArr[] = ['id'=>'bt_form_edit', 'text'=>'修改', 'class'=>'disabled'];
            $this->view->setVar('AddEdit', true);
        }
        if (UserPower::checkUserPower('Faq_Del')) {
            $listButtonArr[] = ['id'=>'bt_list_del', 'text'=>'删除', 'plain'=>'true', 'icon'=>'fa-trash'];
        }
        $formButtonArr[] = ['id'=>'bt_form_back', 'text'=>'返回'];
        $formButtonArr[] = ['id'=>'bt_form_reset', 'text'=>'重置'];
        $listSearchArr[] = ['type' => 'select', 'id' => 'list_classifyId', 'style' => 'width: 200px', 'data' => ['' => '---------问题分类---------']];
        $listSearchArr[] = ['type' => 'text', 'id' => 'list_vague', 'label' => '  搜索：'];
        $this->view->setVars([
            'List'          => Template::createList('List', 'XHFaq_Info', [
                'searchToolbar' => Template::createSearchToolBar($listSearchArr, !!$listButtonArr),
                'buttonToolbar' => Template::createButtonToolBar($listButtonArr),
            ]),
            'Form'          => Template::createForm('XHFaq_Info'),
            'FormButton'    => Template::createButtonToolBar($formButtonArr)
        ]);
        Assets::importMainJs('assets/jquery/ajaxfileupload.js');
        Assets::easyUI('js/faq/faqList.js');
        return  $this->view->pick('faq/faqList');
    }

    /**
     * 获取问答列表
     *
     * create by ck 20160713
     * modify by ck 20160924    获取数据方法更改
     */
    public function getDgDataAction()
    {
        $this->view->disable();
        $sort = $this->request->getPost('sort', 'string');
        $order = $this->request->getPost('order', 'string');
        $classifyId = $this->request->getPost('classifyId', 'int');
        try {
            $parameters = [
                'conditions' => 'bDelete = 0'
            ];
            if ($classifyId) {
                $parameters['conditions'] .= ' AND (iClassifyId = :classifyId: OR iMainClassifyId = :classifyId:)';
                $parameters['bind']['classifyId'] = $classifyId;
            }
            Main::runSearchVagueConditions($parameters['conditions'], ['sQuestion', 'mAnswer']);
            if ($sort && $order) {
                $parameters['conditions'] .= ' ORDER BY '.$sort.' '.$order.', tCreateDate DESC';
            } else {
                $parameters['conditions'] .= ' ORDER BY tCreateDate DESC';
            }
            $result  = Main::runModelPage('\\Admin\\Models\\faq\\XhfaqInfo', $parameters, $this->typenum);
            Main::runUserName(
                $result['rows'],
                ['iCreateUserId' => 'sCreateUserName', 'iLastModifyUserId' => 'sLastModifyUserName']
            );
            foreach ($result['rows'] as &$row) {
                if ($row['iClassifyId']) {
                    $iClassify = XhsysClassification::findFirst($row['iClassifyId']);
                    $row['sClassifyName'] = $iClassify->sName;
                }
                $row['iUserType'] = App::$enum['userType'][$row['iUserType']];
                $row['mAnswer'] = "<div style='text-overflow: ellipsis;max-height: 50px;'>{$row['mAnswer']}</div>";
            }
            return $this->sendJsonResponse($result);
        } catch (\Exception $e) {
            return $this->sendErrorResponse(500, '系统异常', $e->getMessage());
        }
    }

    /**
     * 新增/更新FAQ信息
     *
     * create by ck 20160713
     * modify by ck 20160924
     */
    public function modifyDataAction()
    {
        $this->view->disable();
        if (!$this->request->isPost()) {
            return $this->sendErrorResponse(400, '缺少参数');
        }
        $realData = Main::getRealData($this->request->getPost());
        if ($realData['iClassifyId'] == '0' || $realData['iClassifyId'] == '') {
            return $this->sendErrorResponse(400, '问题分类不能为空');
        } else {
            $realData['iMainClassifyId'] = $this->getParentId($realData['iClassifyId']);
        }
        // 判断对象是否存在
        if (!in_array($realData['bPublic'], array_keys($this->typenum['bPublic']))) {
            return $this->sendErrorResponse(400, '没有该对象');
        }
        // 判断问题类型是否存在
        if (!in_array($realData['iTarget'], array_keys($this->typenum['iTarget']))) {
            return $this->sendErrorResponse(400, '没有该问题类型');
        }
        if ($realData['iTarget'] == 2) {
            if (!$realData['sCoverUrl']) {
                return $this->sendErrorResponse(400, '封面地址不能为空');
            }
        }
        // 判断用户类型是否存在
        if (!in_array($realData['iUserType'], array_keys(App::$enum['userType']))) {
            return $this->sendErrorResponse(400, '没有该用户类型');
        }
        $faq = XhfaqInfo::createRecord($realData);
        if ($faq->iFAQId) {
            if (!UserPower::checkUserPower('Faq_Edit')) {
                return $this->sendErrorResponse(403, '无权限操作');
            }
            $result = $faq->updateData();
        } else {
            if (!UserPower::checkUserPower('Faq_Add')) {
                return $this->sendErrorResponse(403, '无权限操作');
            }
            $result = $faq->insertData();
        }
        if (!$result) {
            return $this->sendErrorResponse(400, '操作失败');
        }
//        UserPower::checkUserPower($faq->iFAQId ? 'Faq_Edit' : 'Faq_Add') or die(Main::showMessageModal('无操作权限！', 109104003));
//        $result = $faq->iFAQId ? $faq->updateData() : $faq->insertData();
//        $result or die(Main::showMessageModal('操作失败！', 109104004));
        Main::createCommitLog('faq', 'FaqList', $faq->iFAQId ? 'edit' : 'add', $faq, $faq->iFAQId);
        return $this->sendSuccessResponse('操作成功');
    }

    /**
     * 根据传入id删除对应记录
     *
     * create by ck 20160714
     * modify by ck 20160924    结构更改
     */
    public function delDataAction()
    {
        $this->view->disable();
        $this->request->isPost() or die;
        UserPower::checkUserPower('Faq_Del') or die('（109104005）无操作权限！');
        $ids = $this->request->getPost('ids');
        XhfaqInfo::deleteRecordById($ids) or die('（109104006）删除失败！');
        echo '删除成功！';
        Main::createCommitLog('faq', 'FaqList', 'del', ['ids' => $ids], null, '批量删除');
    }

    /**
     * 图片上传处理
     *
     * create by gby 20180927
     */
    public function imgUploadAction()
    {
        set_time_limit(0);
        if (!$this->request->hasFiles()) {
            return $this->sendErrorResponse(400, '缺少文件');
        }
        $file = $this->request->getUploadedFiles()[0];
        $filePath = Tool::buildPath(Main::getConfigByName('fileSave')['temp'], $file->getName());
        $file->moveTo($filePath);
        $url = Main::uploadToFileManageSystem($filePath);
        if (!$url) {
            return $this->sendErrorResponse(500, '图片上传失败');
        }
        $response = new stdClass;
        $response->link = $url;
        echo stripslashes(json_encode($response));exit;
    }

    /**
     * 分类管理页面
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface|\Phalcon\Mvc\View
     * create by gby 20180925
     */
    public function classifyListAction()
    {
        if (!Power::exist('Faq_classify')) {
            return $this->sendErrorResponse(403, '抱歉，您没有查看此页面的权限！');
        }
        Assets::sweetAlert2();
        Assets::easyUI();
        Main::showNavPosition();
        $this->view->pick('faq/classifyList');
        Assets::importJs('js/faq/faqClassify.js');
        Assets::importMainJs('assets/xh/xhForm.js');
        Assets::importMainJs('assets/xh/xhTop.js');
        return $this->view->setVars([
            'Edit'=>Power::exist('Faq_classify_Edit'),
            'Add'=>Power::exist('Faq_classify_Add'),
            'Del'=>Power::exist('Faq_classify_Del')
        ]);
    }

    /**
     * 获取所有分类信息
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface|string
     * create by gby 20180925
     */
    public function getClassifyAction()
    {
        if (!Power::exist('Faq_classify')) {
            return $this->sendErrorResponse(403, '无权限操作');
        }
        $id = $this->request->getPost('id', 'int');
        if ($id) {
            // 获取子集
            return json_encode($this->recursionForArray($id));
        }
        $parameters = [
            'conditions' => "bDelete=:bDelete: AND iType=:iType: AND iParentId=:parentId: ",
            'bind' => ['parentId' =>0 , 'bDelete' => 0, 'iType' => 1],
        ];
        $objs = Main::runModelPage('\\Admin\\Models\\sys\\XhsysClassification', $parameters);
        $array = $objs['rows'];
        Main::runUserName($array, ['iCreateUserId' => 'iCreateUserId', 'iLastModifyUserId' => 'iLastModifyUserId']);
        $newArray=[];
        foreach ($array as $key => $value) {
            $newArray['rows'][$key]=$value;
//            $newArray['rows'][$key]['iconCls']='fa fa-group';
            $newArray['rows'][$key]['children']=$this->recursionForArray($value['id']);
            if ($newArray['rows'][$key]['children']) {
                $newArray['rows'][$key]['state']="closed";
            }
        }
        $newArray['total'] = $objs['total'];
        return $this->sendJsonResponse($newArray);
    }

    /**
     * 获取分类详情
     * @return string
     * create by gby 20180925
     */
    public function getClassifyInfoAction()
    {
        $id = $this->request->getPost('id', 'int');
        if (!$id) {
            return $this->sendErrorResponse(400, '缺少参数');
        }
        $obj = XhsysClassification::findFirst($id);
        $jsonArray = $obj->toArray();
        if ($jsonArray['iParentId']==0) {
            $jsonArray['inputPareName']='顶层';
        } else {
            $pObj = XhsysClassification::findFirst($jsonArray['iParentId']);
            $jsonArray['inputPareName']= $pObj->sName;
        }
        return json_encode($jsonArray);
    }

    /**
     * 分类下拉列表  id ,text easyui
     * @return string
     * created by gby 20180925
     */
    public function getClassifyEnumAction()
    {
        $newArray[0]['id']=0;
        $newArray[0]['text']='';
//        $newArray[0]['iconCls']='fa fa-group';
        $newArray[0]['children']=$this->selectRecursion(0);
        return json_encode($newArray);
    }

    /**
     * 搜索下拉框
     * @return string
     */
    public function getSearchEnumAction()
    {
        return json_encode($this->selectRecursion(0));
    }

    /**
     * 添加分类页面
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface|\Phalcon\Mvc\View
     * create by gby 20180925
     */
    public function addClassifyAction()
    {
        if (!Power::exist('Faq_classify_Add')) {
            return $this->sendErrorResponse(403, '无权限操作');
        }
        Assets::importMainJs('assets/xh/xhForm.js');
        Assets::importJs('../customer/js/myMain.js');
        Assets::easyUI('js/faq/faqAddClassify.js');
        return $this->view->pick('faq/classifyForm');
    }

    /**
     * 保存分类信息
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     * create by 20180925
     */
    public function saveClassifyAction()
    {
        $data = $this->request->getPost();
        $id = $this->request->getPost('id', 'int');
        $sTag = $this->request->getPost('sTag', 'string');
        $iParentId = $this->request->getPost('iParentId', 'int');
        $parameters = [
            'conditions' => 'bDelete = 0 AND iType=:iType:',
            'bind' => ['iType' => 1]
        ];
        if ($id) {
            if (!Power::exist('Faq_classify_Edit')) {
                return $this->sendErrorResponse(403, '无操作权限');
            }
        } else {
            if (!Power::exist('Faq_classify_Add')) {
                return $this->sendErrorResponse(403, '无操作权限');
            }
        }
        if (!$data['sName']) {
            return $this->sendErrorResponse(400, '分类名称不能为空！');
        }
        if (!$iParentId) {
            if (!$sTag) {
                return $this->sendErrorResponse(400, '分类标签不能为空！');
            }
        }
        try {
            // 新增分类
            if (!$id) {
                // 判断分类名称是否存在
                if ($data['sName']) {
                    $parameters['conditions'] .= " AND sName = :sName:";
                    $parameters['bind'] += ['sName' => $data['sName']];
                    $sName = XhsysClassification::findFirst($parameters);
                    if ($sName) {
                        return $this->sendErrorResponse(400, '分类名称已存在,请重新输入');
                    }
                    var_dump($sName);
                }
                // 判断分类标签是否存在
                if ($sTag) {
                    $parameters['conditions'] .= " AND sTag = :sTag:";
                    $parameters['bind'] += ['sTag' => $sTag];
                    $stag = XhsysClassification::findFirst($parameters);
                    if ($stag) {
                        return $this->sendErrorResponse(400, '分类标签已存在,请重新输入');
                    }
                }
                $data['iType'] = 1;
                $obj = new XhsysClassification();
            } else {
                // 修改分类
                $obj = XhsysClassification::findFirst($id);
            }
            $obj->assign($data);
            if ($sTag == '') {
                $obj->sTag = null;
            } else {
                $obj->sTag = (strtoupper(trim($sTag)));
            }
            if ($iParentId == '') {
                $obj->iParentId = 0;
            } else {
                $obj->iParentId = $iParentId;
            }
            $result = $obj->save();
            if ($result) {
                if ($id) {
                    return $this->sendSuccessResponse('修改成功');
                } else {
                    return $this->sendSuccessResponse('保存成功');
                }
            } else {
                if ($id) {
                    return $this->sendErrorResponse(500, '修改失败');
                } else {
                    return $this->sendErrorResponse(500, '添加失败');
                }
            }
        } catch (Exception $e) {
            return $this->sendErrorResponse(400, $e->getMessage());
        }
    }

    /**
     * 删除分类
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     * create by gby 20180926
     */
    public function deleteClassifyAction()
    {
        if (!Power::exist('Faq_classify_Del')) {
            return $this->sendErrorResponse(403, '无删除权限');
        }
        $id = $this->request->getPost('id', 'int');
        $obj = XhsysClassification::findFirst($id);
        $obj->bDelete = 1;
        $result=$obj->save();
        if ($result&&$this->recursionForDelete([$id])) {
            return $this->sendSuccessResponse('删除成功');
        } else {
            return $this->sendErrorResponse(400, '删除失败');
        }
    }

    /**
     * 获取分类数据，列表树形展示
     * @param $parentId
     * @return array
     * create by gby 20180926
     */
    public function recursionForArray($parentId)
    {
        $parameters = [
            'conditions' => "bDelete=:bDelete: AND iType=:iType: AND iParentId=:parentId: ",
            'bind' => ['parentId' =>$parentId , 'bDelete' => 0, 'iType' => 1],
        ];
        $objs = XhsysClassification::find($parameters);
        if ($objs==null) {
            return [];
        }
        $array=$objs->toArray();
        Main::runUserName($array, ['iCreateUserId' => 'iCreateUserId', 'iLastModifyUserId' => 'iLastModifyUserId']);
        $newArray=[];
        foreach ($array as $key => $value) {
            $newArray[$key]=$value;
//            $newArray[$key]['iconCls']='fa fa-group';
            $newArray[$key]['children']=$this->recursionForArray($value['id']);
            if ($newArray[$key]['children']) {
                $newArray[$key]['state']="closed";
            }
        }
        return $newArray;
    }

    /**
     * 分类下拉菜单 树型展示
     * @param $parentId
     * @return array
     * create by gby 20180926
     */
    public function selectRecursion($parentId)
    {
        $parameters = [
            'conditions' => "bDelete=:bDelete: AND iType=:iType: AND iParentId=:parentId: ",
            'bind' => ['parentId' =>$parentId , 'bDelete' => 0, 'iType' => 1],
        ];
        $objs = XhsysClassification::find($parameters);
        if ($objs==null) {
            return [];
        }
        $array=$objs->toArray();
        $newArray=[];
        foreach ($array as $key => $value) {
            $newArray[$key]['id']=$value['id'];
            $newArray[$key]['text']=$value['sName'];
//            $newArray[$key]['iconCls']='fa fa-group';
            $newArray[$key]['children']=$this->selectRecursion($value['id']);
            if ($newArray[$key]['children']) {
                $newArray[$key]['state']="closed";
            }
        }
        return $newArray;
    }

    /**
     * 删除当前类下的所有子类
     * @param $array
     * @return bool
     * created by gby 20180926
     */
    public function recursionForDelete($array)
    {
        $objs = XhsysClassification::find([
            'conditions' => 'iParentId in ({ids:array}) AND bDelete=:bDelete: ',
            'bind' => ['ids' => $array,'bDelete' => 0]
        ]);
        $ids=[];
        if ($objs==null) {
            return true;
        }
        foreach ($objs as $obj) {
            $obj->bDelete = 1;
            if (!$obj->save()) {
                return false;
            }
            array_push($ids, $obj->id);
        }
        if ($ids==[]) {
            return true;
        } else {
            return $this->recursionForDelete($ids);
        }
    }

    /**
     * 获取顶级父类Id
     * @param $id
     * @return mixed
     * create by gby 20180927
     */
    public function getParentId($id)
    {
        // 通过id 查找父类id
        $data = XhsysClassification::findFirst($id);
        $iParentId = $data->iParentId;
        $newArray = [];
        if ($iParentId != '0') {
            return $this->getParentId($iParentId);
        } else {
            $newArray['iParentId'] = $id;
            return $id;
        }
    }
}
